/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.user.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * 自定义流控异常处理器。
 *
 * @author Denvie
 * @date 2022/4/2
 * @since 1.0.0
 */
@Slf4j
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String message = handlerBlockException(getClass(), e);
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        objectMapper.writeValue(response.getWriter(), message);
    }

    /**
     * 处理流控异常
     */
    public String handlerBlockException(Class<?> from, BlockException e) {
        log.error("{} ====> {}", from.getSimpleName(), e.getRule());
        String message;
        if (e instanceof FlowException) {
            message = "接口限流了";
        } else if (e instanceof DegradeException) {
            message = "服务降级了";
        } else if (e instanceof ParamFlowException) {
            message = "热点参数限流了";
        } else if (e instanceof SystemBlockException) {
            message = "触发系统保护规则了";
        } else if (e instanceof AuthorityException) {
            message = "授权规则不通过";
        } else {
            message = e.getMessage();
        }
        log.error(message);
        return message;
    }
}
